import { IBizLabTemplate } from "@ibizlab/template";

/**
 * 加 运算助手 {{FormHelper 12 412}} {{FormHelper '124' '512'}}
 *
 * @export
 * @class FormHelper
 */
export class FormHelper {
  /**
   * Creates an instance of FormHelper.
   * @param {IBizLabTemplate} template
   * @memberof FormHelper
   */
  constructor(template: IBizLabTemplate) {
    template.engine.registerHelper("formHelper", (...args: unknown[]) => {
      const type = args[0];
			const ctrl = args[1] as any;
      switch (type) {
        case 'GETDO':
          return this.getFormDO(ctrl);
        default:
          return '';
      }
    });
  }

  /**
   * 获取表单DO
   *
   * @private
   * @param {*} ctrl
   * @return {*}  {string}
   * @memberof FormHelper
   */
  private getFormDO(ctrl: any): string {
    if (!ctrl || !ctrl.psAppDataEntity) {
      return '';
    }
    const keys: string[] = [];
    const noFieldKey: string[] = [];
    const getDetail = (detail: any) => {
      let key: string = '';
      //  多表单部件（重复器）
      if (detail.detailType === 'MDCTRL' && detail.contentType === 'REPEATER') {
        key = (detail.psAppDEField ? detail.psAppDEField.codeName : detail.fieldName ? detail.fieldName : detail.codeName).toLowerCase();
      }
      //  表单项
      if (detail.detailType === 'FORMITEM') {
        if (detail.psAppDEField) {
          key = detail.psAppDEField.codeName.toLowerCase();
        } else {
          if (noFieldKey.indexOf(detail.id.toLowerCase()) === -1) {
            noFieldKey.push(detail.id.toLowerCase());
          }
        }
      }
      if (key && keys.indexOf(key) === -1) {
        keys.push(key);
      }
      if (detail.detailType !== 'MDCTRL' && detail.psDEFormDetails && detail.psDEFormDetails.length > 0) {
        detail.psDEFormDetails.forEach((children: any) => {
          getDetail(children);
        });
      }
      if (detail.psDEFormTabPages && detail.psDEFormTabPages.length > 0) {
        detail.psDEFormTabPages.forEach((children: any) => {
          getDetail(children);
        });
      }
    }
    if (ctrl.psDEFormPages) {
      ctrl.psDEFormPages.forEach((detail: any) => {
        getDetail(detail);
      })
    }
    if (ctrl.psDEFormItems) {
      ctrl.psDEFormItems.forEach((item: any) => {
        const id = (item.id || '').toLowerCase();
        if (id.startsWith('srf')) {
          if (item.psAppDEField) {
            if (keys.indexOf(item.psAppDEField.codeName.toLowerCase()) === -1) {
              keys.push(item.psAppDEField.codeName.toLowerCase())
            }
          }
        }
      });
    }
    let result: string = '';
    keys.forEach((key: string, index: number) => {
      result += `${result !== '' ? '\n' : ''}${key}: this.$DO.${key},`
    });
    noFieldKey.forEach((key: string) => {
      result += `${result !== '' ? '\n' : ''}${key}: this.${key},`;
    })
    return result;
  }
}
